<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>题库管理 - 智慧教育考试系统</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

  <!-- 配置Tailwind自定义主题 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#36D399',
            accent: '#FF9F43',
            neutral: '#F8FAFC',
            'neutral-dark': '#334155',
          },
          fontFamily: {
            inter: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .card-shadow {
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      }
      .nav-hover {
        @apply transition-all duration-300 hover:bg-primary/10 hover:text-primary;
      }
      .btn-primary {
        @apply bg-primary text-white px-4 py-2 rounded-lg transition-all duration-300 hover:bg-primary/90 active:bg-primary/80;
      }
      .btn-secondary {
        @apply bg-white border border-gray-200 text-neutral-dark px-4 py-2 rounded-lg transition-all duration-300 hover:bg-gray-50 active:bg-gray-100;
      }
      .btn-danger {
        @apply bg-red-50 text-red-600 border border-red-200 px-3 py-1 rounded-lg transition-all duration-300 hover:bg-red-100 active:bg-red-200;
      }
      .btn-action {
        @apply bg-blue-50 text-blue-600 border border-blue-200 px-3 py-1 rounded-lg transition-all duration-300 hover:bg-blue-100 active:bg-blue-200;
      }
    }
  </style>
</head>
<body class="font-inter bg-gray-50 text-neutral-dark min-h-screen flex flex-col">
  <!-- 顶部导航栏 -->
  <header class="bg-white border-b border-gray-200 sticky top-0 z-30">
    <div class="container mx-auto px-4 py-3 flex items-center justify-between">
      <div class="flex items-center space-x-2">
        <i class="fa fa-graduation-cap text-primary text-2xl"></i>
        <h1 class="text-xl font-bold text-primary">智慧教育考试系统</h1>
      </div>

      <div class="flex items-center space-x-6">
        <div class="hidden md:flex items-center space-x-4">
          <button class="text-gray-500 hover:text-primary transition-colors">
            <i class="fa fa-bell-o"></i>
          </button>
          <button class="text-gray-500 hover:text-primary transition-colors">
            <i class="fa fa-cog"></i>
          </button>
        </div>

        <div class="flex items-center space-x-2">
          <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary">
            <i class="fa fa-user"></i>
          </div>
          <span class="hidden md:inline">张老师</span>
        </div>
      </div>
    </div>
  </header>

  <!-- 主内容区 -->
  <main class="flex-1 flex flex-col md:flex-row">
    <!-- 左侧导航 -->
    <aside class="w-full md:w-64 bg-white border-r border-gray-200 md:h-[calc(100vh-60px)] sticky md:sticky top-[60px] z-20">
      <!-- 角色切换 -->
      <div class="p-4 border-b border-gray-200">
        <h2 class="text-sm font-medium text-gray-500 mb-2">角色切换</h2>
        <div class="flex rounded-lg overflow-hidden border border-gray-200">
          <button id="teacher-tab" class="flex-1 py-2 px-3 bg-primary text-white text-sm font-medium">
            教师端
          </button>
          <button id="student-tab" class="flex-1 py-2 px-3 bg-white text-gray-600 text-sm font-medium hover:bg-gray-50">
            学生端
          </button>
        </div>
      </div>

      <!-- 教师导航菜单 -->
      <nav id="teacher-nav" class="p-2">
        <ul class="space-y-1">
          <li>
            <a href="/home" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-bar-chart w-5 text-center"></i>
              <span>教师控制台</span>
            </a>
          </li>
          <li>
            <a href="/Publish_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-pencil-square-o w-5 text-center"></i>
              <span>发布考试</span>
            </a>
          </li>
          <li>
            <a href="/History_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-history w-5 text-center"></i>
              <span>历史考试</span>
            </a>
          </li>
          <li>
            <a href="/Set_questions" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-magic w-5 text-center"></i>
              <span>一键出题</span>
            </a>
          </li>
          <li>
            <a href="/Question_Bank" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover text-primary bg-primary/10">
              <i class="fa fa-book w-5 text-center"></i>
              <span>题库管理</span>
            </a>
          </li>
          <li>
            <a href="/stu_management" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-users w-5 text-center"></i>
              <span>学生管理</span>
            </a>
          </li>
          <li>
            <a href="/class_management" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-th-large w-5 text-center"></i>
              <span>班级管理</span>
            </a>
          </li>
        </ul>
      </nav>

      <!-- 学生导航菜单 (默认隐藏) -->
      <nav id="student-nav" class="p-2 hidden">
        <ul class="space-y-1">
          <li>
            <a href="/Exam_record" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-file-text-o w-5 text-center"></i>
              <span>个人考试记录</span>
            </a>
          </li>
          <li>
            <a href="/Waiting_exam" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-clock-o w-5 text-center"></i>
              <span>待考试</span>
              <span class="ml-auto bg-accent text-white text-xs px-2 py-0.5 rounded-full">3</span>
            </a>
          </li>
          <li>
            <a href="/Mistake_question" class="flex items-center space-x-3 px-3 py-2.5 rounded-lg nav-hover">
              <i class="fa fa-exclamation-circle w-5 text-center"></i>
              <span>错题本</span>
            </a>
          </li>
        </ul>
      </nav>
    </aside>

    <!-- 右侧内容区 -->
    <div class="flex-1 p-4 md:p-6 overflow-auto">
      <div class="mb-6">
        <div class="flex items-center">
          <a href="#" class="text-gray-500 hover:text-primary mr-2">
            <i class="fa fa-arrow-left"></i>
          </a>
          <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold">题库管理</h2>
        </div>
        <p class="text-gray-500 mt-1">管理所有试题库，支持创建、导入和删除操作</p>
      </div>

      <!-- 搜索与操作区域 -->
        <div class="bg-white rounded-xl p-5 card-shadow mb-6">
            <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
                <div class="flex flex-wrap items-center gap-3">
                    <div class="flex items-center space-x-2">
                        <select id="subject-filter" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
                            <option value="all">全部学科</option>
                        </select>
                        <select id="type-filter" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
                            <option value="all">全部题型</option>
                        </select>
                        <select id="grade-filter" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
                            <option value="all">全部年级</option>
                        </select>
                        <select id="knowledge-filter" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors">
                            <option value="all">全部知识点</option>
                        </select>

                    </div>
                </div>
                <div class="flex items-center space-x-2">
                <!-- 搜索框 -->
                <div class="relative">
                    <input type="text"
                           id="search-input"
                           placeholder="搜索题目..."
                           class="border border-gray-300 rounded-lg pl-10 pr-4 py-2 text-sm focus:ring-2 focus:ring-primary/50 focus:border-primary transition-colors w-64">
                    <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                </div>
                <button id="search-btn" class="btn-primary">
                    搜索
                </button>
                <button id="reset-btn" class="btn-secondary">
                    重置
                </button>
                </div>
            </div>
        </div>

      <!-- 题库表格 -->
      <div class="bg-white rounded-xl card-shadow overflow-hidden">
        <div class="overflow-x-auto">
          <table class="w-full min-w-[800px]">
            <thead>
              <tr class="bg-gray-50 text-left">
                <th class="px-6 py-4 text-sm font-medium text-gray-600">
                  <div class="flex items-center">
                    <input type="checkbox" class="mr-2">
                    序号
                  </div>
                </th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">学科</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">问题</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">题目类型</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">班级</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">分值</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">天数</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600">知识点</th>
                <th class="px-6 py-4 text-sm font-medium text-gray-600 text-right">操作</th>
              </tr>
            </thead>
            <tbody class="divide-y divide-gray-100">

            </tbody>
          </table>
        </div>

        <!-- 分页 -->
        <div class="px-6 py-4 border-t border-gray-100 flex flex-col sm:flex-row justify-between items-center">
          <p class="text-sm text-gray-500 mb-4 sm:mb-0">显示 1 至 5 条，共 24 条记录</p>
          <div class="flex items-center space-x-1">
            <button class="w-9 h-9 flex items-center justify-center rounded border border-gray-200 text-gray-500 hover:border-primary hover:text-primary disabled:opacity-50 disabled:cursor-not-allowed" disabled>
              <i class="fa fa-angle-left"></i>
            </button>
            <button class="w-9 h-9 flex items-center justify-center rounded bg-primary text-white">1</button>
            <button class="w-9 h-9 flex items-center justify-center rounded border border-gray-200 hover:border-primary hover:text-primary">2</button>
            <button class="w-9 h-9 flex items-center justify-center rounded border border-gray-200 hover:border-primary hover:text-primary">3</button>
            <button class="w-9 h-9 flex items-center justify-center rounded border border-gray-200 hover:border-primary hover:text-primary">4</button>
            <button class="w-9 h-9 flex items-center justify-center rounded border border-gray-200 hover:border-primary hover:text-primary">5</button>
            <button class="w-9 h-9 flex items-center justify-center rounded border border-gray-200 text-gray-700 hover:border-primary hover:text-primary">
              <i class="fa fa-angle-right"></i>
            </button>
          </div>
        </div>
      </div>


  <!-- 页脚 -->
  <footer class="bg-white border-t border-gray-200 py-4">
    <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
      <p>© 2025 智慧教育考试系统 版权所有</p>
    </div>
  </footer>

<script>
// 全局状态
let currentState = {
    page: 1,
    per_page: 10,
    subject: '',
    type: '',
    grade: '',
    knowledge:'',
    search: '',

};

// DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    setupRoleSwitch();
    loadFilters();
    loadQuestionBank();
    setupEventListeners();
});

// 设置事件监听器
function setupEventListeners() {

    // 学科筛选
    document.getElementById('subject-filter').addEventListener('change', function(e) {
        currentState.subject = e.target.value==='all'?'':e.target.value;
        currentState.page = 1;
        loadQuestionBank();
    });

    // 题型筛选
    document.getElementById('type-filter').addEventListener('change', function(e) {
        currentState.type = e.target.value==='all'?'':e.target.value;
        currentState.page = 1;
        loadQuestionBank();
    });

    // 年级筛选
    document.getElementById('grade-filter').addEventListener('change', function(e) {
        currentState.grade = e.target.value==='all'?'':e.target.value;
        currentState.page = 1;
        loadQuestionBank();
    });
    // 知识点筛选
    document.getElementById('knowledge-filter').addEventListener('change', function(e) {
        currentState.knowledge = e.target.value==='all'?'':e.target.value;
        currentState.page = 1;
        loadQuestionBank();
    });
    // 搜索功能
    document.getElementById('search-btn').addEventListener('click', function() {
        performSearch();
    });
    // 重置功能
    document.getElementById('reset-btn').addEventListener('click', function() {
        resetFilters();
    });

}
// 执行搜索
function performSearch() {
    const searchInput = document.getElementById('search-input');
    currentState.search = searchInput.value.trim();
    currentState.page = 1;
    loadQuestionBank();
}
// 加载筛选条件
async function loadFilters() {
    try {
        const response = await fetch('/api/question_bank/filters');
        const result = await response.json();

        if (result.success) {
            const filters = result.data;
            updateFilterOptions(filters);
        }
    } catch (error) {
        console.error('加载筛选条件失败:', error);
    }
}

// 更新筛选选项
function updateFilterOptions(filters) {
    // 更新学科选项
    const subjectSelect = document.getElementById('subject-filter');
    subjectSelect.innerHTML = '<option value="all">全部学科</option>';
    filters.subjects.forEach(subject => {
        const option = document.createElement('option');
        option.value = subject;
        option.textContent = subject;
        subjectSelect.appendChild(option);
    });

    // 更新题型选项
    const typeSelect = document.getElementById('type-filter');
    typeSelect.innerHTML = '<option value="all">全部题型</option>';
    filters.types.forEach(type => {
        const option = document.createElement('option');
        option.value = type;
        option.textContent = type;
        typeSelect.appendChild(option);
    });

    // 更新年级选项
    const gradeSelect = document.getElementById('grade-filter');
    gradeSelect.innerHTML = '<option value="all">全部年级</option>';
    filters.grades.forEach(grade => {
            const option = document.createElement('option');
            option.value = grade;
            option.textContent = grade;
            gradeSelect.appendChild(option);
        });
    const knowledgeSelect = document.getElementById('knowledge-filter');
    knowledgeSelect.innerHTML = '<option value="all">知识点</option>';
    if (filters.knowledges) {
    filters.knowledges.forEach(knowledge => {
        if (knowledge) { // 过滤空值
            const option = document.createElement('option');
            option.value = knowledge;
            option.textContent = knowledge;
            knowledgeSelect.appendChild(option);
        }
        });
    }
}

// 加载题库数据
async function loadQuestionBank() {
    try {
        // 显示加载状态
        showLoading();

        // 构建查询参数
        const params = new URLSearchParams({
            page: currentState.page,
            per_page: currentState.per_page
        });

        if (currentState.subject && currentState.subject !== 'all') {
            params.append('subject', currentState.subject);
        }
        if (currentState.type && currentState.type !== 'all') {
            params.append('type', currentState.type);
        }
        if (currentState.grade && currentState.grade !== 'all') {
            params.append('grade', currentState.grade);
        }
        if (currentState.knowledge && currentState.knowledge !== 'all') {
            params.append('knowledge', currentState.knowledge);
        }
        if (currentState.search) {
            params.append('search', currentState.search);
        }
        console.log('请求参数:', params.toString());
        const response = await fetch(`/api/question_bank?${params}`);
        const result = await response.json();

        if (result.success) {
            //保存页数信息
            currentState.totalPages = result.data.pagination.pages;
            renderQuestionTable(result.data.questions);
            renderPagination(result.data.pagination);
        } else {
            showError('加载数据失败');
        }
    } catch (error) {
        console.error('加载题库数据失败:', error);
        showError('网络错误，请重试');
    }
}


//重置筛选条件
function resetFilters() {
    currentState = {
        page: 1,
        per_page: 10,
        subject: '',
        type: '',
        grade: '',
        knowledge: '',
        search: ''
    };

    document.getElementById('subject-filter').value = 'all';
    document.getElementById('type-filter').value = 'all';
    document.getElementById('grade-filter').value = 'all';
    document.getElementById('knowledge-filter').value = 'all';
    document.getElementById('search-input').value = '';

    loadQuestionBank();
}
// 渲染题目表格
function renderQuestionTable(questions) {
    const tbody = document.querySelector('tbody');

    if (questions.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="9" class="px-6 py-8 text-center text-gray-500">
                    <i class="fa fa-inbox text-4xl mb-2 opacity-50"></i>
                    <p>${currentState.search ? '没有搜索结果' : '没有题目'}</p>
                </td>
            </tr>
        `;
        return;
    }

    tbody.innerHTML = questions.map((question, index) => `
        <tr class="hover:bg-gray-50 transition-colors">
            <td class="px-6 py-4">
                <div class="flex items-center">
                    <input type="checkbox" class="mr-2 question-checkbox" value="${question.id}">
                    ${(currentState.page - 1) * currentState.per_page + index + 1}
                </div>
            </td>
            <td class="px-6 py-4 text-sm">${escapeHtml(question.subject || '')}</td>
            <td class="px-6 py-4">
                <div class="max-w-xs truncate" title="${escapeHtml(question.title)}">
                    ${escapeHtml(question.title)}
                </div>
            </td>
            <td class="px-6 py-4">
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium
                    ${getTypeBadgeClass(question.type)}">
                    ${escapeHtml(question.type || '')}
                </span>
            </td>
            <td class="px-6 py-4 text-sm">${escapeHtml(question.grade || '')}</td>
            <td class="px-6 py-4 text-sm">${question.score}</td>
            <td class="px-6 py-4 text-sm">${question.day}</td>
            <td class="px-6 py-4 text-sm">
                <span class="inline-block max-w-xs truncate" title=“${escapeHtml(question.knowledge || '')}">
                    ${escapeHtml(question.knowledge || '')}
                </span>
            </td>
            <td class="px-6 py-4 text-right">
                <div class="flex justify-end space-x-2">
                    <button class="btn-action" onclick="editQuestion(${question.id})">
                        <i class="fa fa-edit"></i> 编辑
                    </button>
                    <button class="btn-danger" onclick="deleteQuestion(${question.id})">
                        <i class="fa fa-trash"></i> 删除
                    </button>
                </div>
            </td>
        </tr>
    `).join('');
}

// 获取题型标签样式
function getTypeBadgeClass(type) {
    const classMap = {
        '选择题': 'bg-blue-100 text-blue-800',
        '多选题': 'bg-purple-100 text-purple-800',
        '填空题': 'bg-green-100 text-green-800',
        '简答题': 'bg-orange-100 text-orange-800'
    };
    return classMap[type] || 'bg-gray-100 text-gray-800';
}

// 渲染分页
function renderPagination(pagination) {
    const paginationContainer = document.querySelector('.px-6.py-4.border-t.border-gray-100');

    if (!paginationContainer) {
        console.error('分页容器未找到');
        return;
    }

    const startItem = ((currentState.page - 1) * currentState.per_page) + 1;
    const endItem = Math.min(currentState.page * currentState.per_page, pagination.total);

    paginationContainer.innerHTML = `
        <div class="flex flex-col sm:flex-row justify-between items-center">
            <p class="text-sm text-gray-500 mb-4 sm:mb-0">
                显示 ${startItem} 至 ${endItem} 条，共 ${pagination.total} 条记录
            </p>
            <div class="flex items-center space-x-1">
                <button class="w-9 h-9 flex items-center justify-center rounded border border-gray-200 text-gray-500 hover:border-primary hover:text-primary transition-colors ${currentState.page === 1 ? 'opacity-50 cursor-not-allowed' : ''}"
                    ${currentState.page === 1 ? 'disabled' : ''}
                    onclick="changePage(${currentState.page - 1})">
                    <i class="fa fa-angle-left"></i>
                </button>

                ${generatePageButtons(currentState.page, pagination.pages)}

                <button class="w-9 h-9 flex items-center justify-center rounded border border-gray-200 text-gray-500 hover:border-primary hover:text-primary transition-colors ${currentState.page === pagination.pages ? 'opacity-50 cursor-not-allowed' : ''}"
                    ${currentState.page === pagination.pages ? 'disabled' : ''}
                    onclick="changePage(${currentState.page + 1})">
                    <i class="fa fa-angle-right"></i>
                </button>
            </div>
        </div>
    `;
}
// 生成页码按钮
function generatePageButtons(currentPage, totalPages) {
    if (totalPages <= 0) return '';

    let startPage, endPage;

    if (totalPages <= 5) {
        // 总页数少于5页，显示所有页码
        startPage = 1;
        endPage = totalPages;
    } else {
        // 总页数多于5页，显示当前页附近的页码
        if (currentPage <= 3) {
            startPage = 1;
            endPage = 5;
        } else if (currentPage + 2 >= totalPages) {
            startPage = totalPages - 4;
            endPage = totalPages;
        } else {
            startPage = currentPage - 2;
            endPage = currentPage + 2;
        }
    }

    let buttons = '';
    for (let i = startPage; i <= endPage; i++) {
        const isActive = i === currentPage;
        buttons += `
            <button class="w-9 h-9 flex items-center justify-center rounded border transition-colors ${isActive ? 'bg-primary text-white border-primary' : 'border-gray-200 text-gray-700 hover:border-primary hover:text-primary'}"
                onclick="changePage(${i})">
                ${i}
            </button>
        `;
    }

    return buttons;
}

// 分页按钮点击事件
function changePage(page) {
    if (page < 1 || page > getTotalPages()) {
        console.log('无效的页码',page);
        return;
    }
    console.log('切换到页码', page);
    currentState.page = page;
    loadQuestionBank();
}

// 获取总页数（需要从服务器响应中获取）
function getTotalPages() {
    // 这里需要从服务器响应中获取实际的总页数
    return currentState.totalPages || 1;
}
// 删除题目
async function deleteQuestion(questionId) {
    if (!confirm('确定要删除这道题目吗？')) return;

    try {
        const response = await fetch(`/api/question_bank/${questionId}`, {
            method: 'DELETE'
        });
        const result = await response.json();

        if (result.success) {
            showSuccess('删除成功');
            loadQuestionBank();
        } else {
            showError(result.error || '删除失败');
        }
    } catch (error) {
        console.error('删除题目失败:', error);
        showError('网络错误，请重试');
    }
}

// 编辑题目
async function editQuestion(questionId) {
    try {
        // 获取题目详情
        const response = await fetch(`/api/question_bank/${questionId}`);
        const result = await response.json();

        if (result.success) {
            showEditModal(result.data);
        } else {
            alert('获取题目失败');
        }
    } catch (error) {
        console.error('编辑题目失败:', error);
        alert('网络错误');
    }
}

// 显示编辑模态框
function showEditModal(question) {
    const modal = document.createElement('div');
    modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
    modal.innerHTML = `
        <div class="bg-white rounded-xl w-full max-w-md mx-4 max-h-[90vh] overflow-y-auto">
            <div class="p-4 border-b">
                <h3 class="text-lg font-semibold">编辑题目</h3>
            </div>

            <div class="p-4 space-y-3">
                <div>
                    <label class="block text-sm text-gray-600 mb-1">题目</label>
                    <textarea id="edit-title" class="w-full border rounded p-2 text-sm" rows="3">${question.title || ''}</textarea>
                </div>

                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="block text-sm text-gray-600 mb-1">学科</label>
                        <input type="text" id="edit-subject" class="w-full border rounded p-2 text-sm" value="${question.subject || ''}">
                    </div>
                    <div>
                        <label class="block text-sm text-gray-600 mb-1">类型</label>
                        <select id="edit-type" class="w-full border rounded p-2 text-sm" onchange="toggleOptionsField()">
                            <option value="选择题" ${question.type === '选择题' ? 'selected' : ''}>选择题</option>
                            <option value="多选题" ${question.type === '多选题' ? 'selected' : ''}>多选题</option>
                            <option value="填空题" ${question.type === '填空题' ? 'selected' : ''}>填空题</option>
                            <option value="简答题" ${question.type === '简答题' ? 'selected' : ''}>简答题</option>
                        </select>
                    </div>
                </div>

                <div id="options-field" class="${question.type === '选择题' || question.type === '多选题' ? '' : 'hidden'}">
                    <label class="block text-sm text-gray-600 mb-1">选项</label>
                    <textarea id="edit-option" class="w-full border rounded p-2 text-sm" rows="3" placeholder="格式：A.选项1 B.选项2 C.选项3 D.选项4">${question.option || ''}</textarea>
                </div>

                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="block text-sm text-gray-600 mb-1">年级</label>
                        <input type="text" id="edit-grade" class="w-full border rounded p-2 text-sm" value="${question.grade || ''}">
                    </div>
                    <div>
                        <label class="block text-sm text-gray-600 mb-1">分值</label>
                        <input type="number" id="edit-score" class="w-full border rounded p-2 text-sm" value="${question.score || 1}">
                    </div>
                </div>

                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="block text-sm text-gray-600 mb-1">天数</label>
                        <input type="number" id="edit-day" class="w-full border rounded p-2 text-sm" value="${question.day || 1}">
                    </div>
                    <div>
                        <label class="block text-sm text-gray-600 mb-1">知识点</label>
                        <input type="text" id="edit-knowledge" class="w-full border rounded p-2 text-sm" value="${question.knowledge || ''}">
                    </div>
                </div>

                <div>
                    <label class="block text-sm text-gray-600 mb-1">答案</label>
                    <textarea id="edit-answer" class="w-full border rounded p-2 text-sm" rows="2">${question.answer || ''}</textarea>
                </div>
            </div>

            <div class="p-4 border-t flex justify-end space-x-2">
                <button onclick="this.closest('.fixed').remove()" class="px-4 py-2 border rounded text-sm">取消</button>
                <button onclick="saveQuestionEdit(${question.id}, this)" class="px-4 py-2 bg-primary text-white rounded text-sm">保存</button>
            </div>
        </div>
    `;

    document.body.appendChild(modal);

    // 初始化显示选项字段
    setTimeout(() => toggleOptionsField(), 0);
}

// 切换选项字段显示
function toggleOptionsField() {
    const typeSelect = document.getElementById('edit-type');
    const optionsField = document.getElementById('options-field');

    if (typeSelect && optionsField) {
        if (typeSelect.value === '选择题' || typeSelect.value === '多选题') {
            optionsField.classList.remove('hidden');
        } else {
            optionsField.classList.add('hidden');
        }
    }
}

// 保存编辑
async function saveQuestionEdit(questionId, button) {
    const modal = button.closest('.fixed');

    const formData = {
        title: document.getElementById('edit-title').value.trim(),
        subject: document.getElementById('edit-subject').value.trim(),
        type: document.getElementById('edit-type').value,
        grade: document.getElementById('edit-grade').value.trim(),
        score: parseInt(document.getElementById('edit-score').value) || 1,
        day: parseInt(document.getElementById('edit-day').value) || 1,
        knowledge: document.getElementById('edit-knowledge').value.trim(),
        answer: document.getElementById('edit-answer').value.trim()
    };

    // 如果是选择题或多选题，添加选项字段
    const questionType = document.getElementById('edit-type').value;
    if (questionType === '选择题' || questionType === '多选题') {
        formData.option = document.getElementById('edit-option').value.trim();

        // 验证选项格式
        if (!formData.option) {
            alert('请填写选项');
            return;
        }
    }

    // 简单验证
    if (!formData.title || !formData.subject || !formData.answer) {
        alert('请填写完整信息');
        return;
    }

    try {
        button.disabled = true;
        button.textContent = '保存中...';

        const response = await fetch(`/api/question_bank/${questionId}`, {
            method: 'PUT',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(formData)
        });

        const result = await response.json();

        if (result.success) {
            modal.remove();
            loadQuestionBank(); // 刷新表格
            alert('更新成功');
        } else {
            alert(result.error || '更新失败');
        }
    } catch (error) {
        console.error('保存失败:', error);
        alert('网络错误');
    } finally {
        button.disabled = false;
        button.textContent = '保存';
    }
}

// 显示加载状态
function showLoading() {
    const tbody = document.querySelector('tbody');
    tbody.innerHTML = `
        <tr>
            <td colspan="9" class="px-6 py-8 text-center text-gray-500">
                <div class="flex items-center justify-center">
                    <div class="animate-spin rounded-full h-6 w-6 border-b-2 border-primary mr-2"></div>
                    加载中...
                </div>
            </td>
        </tr>
    `;
}

// 显示成功消息
function showSuccess(message) {
    // 这里可以添加更美观的通知组件
    alert('成功: ' + message);
}

// 显示错误消息
function showError(message) {
    // 这里可以添加更美观的错误通知组件
    alert('错误: ' + message);
}

// HTML转义函数
function escapeHtml(unsafe) {
    if (!unsafe) return '';
    return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

// 角色切换功能（原有的）
const setupRoleSwitch = () => {
    const teacherTab = document.getElementById('teacher-tab');
    const studentTab = document.getElementById('student-tab');
    const teacherNav = document.getElementById('teacher-nav');
    const studentNav = document.getElementById('student-nav');

    teacherTab.addEventListener('click', () => {
        teacherTab.classList.add('bg-primary', 'text-white');
        teacherTab.classList.remove('bg-white', 'text-gray-600', 'hover:bg-gray-50');
        studentTab.classList.add('bg-white', 'text-gray-600', 'hover:bg-gray-50');
        studentTab.classList.remove('bg-primary', 'text-white');
        teacherNav.classList.remove('hidden');
        studentNav.classList.add('hidden');
    });

};

// 添加分页按钮样式
const style = document.createElement('style');
style.textContent = `
    .pagination-btn {
        width: 2.25rem;
        height: 2.25rem;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 1px solid #e5e7eb;
        border-radius: 0.375rem;
        color: #6b7280;
        transition: all 0.2s;
    }
    .pagination-btn:hover:not(.disabled) {
        border-color: #165DFF;
        color: #165DFF;
    }
    .pagination-btn.active {
        background-color: #165DFF;
        color: white;
        border-color: #165DFF;
    }
    .pagination-btn.disabled {
        opacity: 0.5;
        cursor: not-allowed;
    }
`;
document.head.appendChild(style);
</script>
    </div>
  </main>
</body>
</html>